import React from "react";

export default class ProcessBar extends React.PureComponent {
    constructor(props) {
        super(props);

        this.parentDefaultStyle = {
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            width: 0,
            height: 2,
            zIndex: 2000,
            transition: 'width 10s cubic-bezier(0, 1, 0.3, 1)',
            boxShadow: '#40a9ff 0px 0px 10px'
        };
        this.barDefaultStyle = {
            width: '100%',
            height: 2,
            backgroundColor: '#E02926',
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0
        };
        this.state = {
            parentStyle: this.parentDefaultStyle,
            barStyle: this.barDefaultStyle
        };
    }

    componentDidMount(){
        this.handleChange(this.props.loading);
    }

    componentWillReceiveProps(nextProps){
        if(this.props.loading && !nextProps.loading){
            this.handleChange(false);
        }
        else if(!this.props.loading && nextProps.loading){
            this.handleChange(true);
        }
    }

    render(){
        const {parentStyle, barStyle} = this.state;
        return (
            <div style={parentStyle} onTransitionEnd={this.hanldeTransitionEnd}>
                <div style={barStyle}>
                    &nbsp;
                </div>
            </div>
        );
    }

    handleChange = (show) => {
        setTimeout(() => {
            if(show){
                this.setState({
                    parentStyle: {...this.parentDefaultStyle, width: '80%'}
                });
            }else{
                this.setState({
                    parentStyle: {...this.parentDefaultStyle, width: '100%', transition: 'width 400ms ease'}
                });
            }
        }, 1);
    };

    hanldeTransitionEnd = () => {
        this.setState({
            parentStyle: {...this.parentDefaultStyle, width: '0', transition: 'width 0ms'}
        });
    };
}
